package com.konsung.ksdc.manager.community;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.netbean.EmpNetBean;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.ImageUtils;
import com.konsung.ksdc.common.utils.PhotoUtils;
import com.konsung.ksdc.common.utils.PreferenceUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.common.widget.ConfirmPopupWindow;
import com.konsung.ksdc.common.widget.TakePicBottomPop;
import com.konsung.ksdc.common.widget.WaitingDialog;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.appmain.LoginActivity;
import com.konsung.ksdc.manager.user.ChangePhoneCheckActivity;
import com.konsung.ksdc.manager.user.QRCodeActivity;
import com.konsung.ksdc.service.MqttService;
import com.squareup.picasso.Picasso;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 创建者     kgh
 * 创建时间   2016/6/14 18:29
 * 描述   ${TODO}
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */
public class MeIndexActivity extends Activity {
    private static final String NO_NOTE = "暂无签名";
    @Bind(R.id.iv_me_pic)
    ImageView ivMePic;
    @Bind(R.id.et_nick_name)
    EditText etNickName;
    @Bind(R.id.tv_user_name)
    TextView tvUserName;
    @Bind(R.id.et_name)
    EditText etName;
    @Bind(R.id.tv_telephone)
    TextView tvTelephone;
    @Bind(R.id.et_addr)
    EditText etAddr;
    @Bind(R.id.et_note)
    EditText etNote;

    @Bind(R.id.iv_back)
    ImageView back;
    @Bind(R.id.ll_phone_container)
    LinearLayout llPhoneContainer;

    @Bind(R.id.tv_edit_index)
    TextView tvEditIndex;
    @Bind(R.id.tv_save)
    TextView tvSave;
    @Bind(R.id.tv_exit)
    TextView btnExit;
    @Bind(R.id.rl_qr_code)
    RelativeLayout rlQrCode;

    private ConfirmPopupWindow popupWindow;
    private TakePicBottomPop mPopWindom;
    private Uri imageUri;
    public static final int TAKE_PHOTO = 1;
    public static final int CROP_PHOTO = 2;
    public static final int SELECT_PIC = 3;
    private WaitingDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_index);
        ButterKnife.bind(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        setComponentEnable(false);

        renderPanel();

        // 初始化控件事件
        initEvent();
    }

    /**
     * 设置控件可用性
     * @param enable 是否可用
     */
    private void setComponentEnable(boolean enable) {
        ivMePic.setEnabled(enable);
        etNickName.setEnabled(enable);
        etName.setEnabled(enable);
        llPhoneContainer.setEnabled(enable);
        etAddr.setEnabled(enable);
        etNote.setEnabled(enable);
    }

    /**
     * 初始化面板数据
     */
    private void renderPanel() {
        if (NetConfig.currentUser == null) {
            return;
        }
        initUserInfo();

        RequestUtils.findEmployeeByUserId(NetConfig.currentUser.getUserId(),
                new RequestCallback() {

                    @Override
                    public void onError(Call call, Exception e) {
                        e.printStackTrace();
                        Toast.makeText(MeIndexActivity.this, getString(R.string.chat_load_failed),
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        EmpNetBean bean = responseBean.getEntity(EmpNetBean.class);
                        initEmpInfo(bean);
                    }
                });
    }

    /**
     * 初始化USER基础信息
     */
    private void initUserInfo() {
        RegisterUserNetBean user = NetConfig.currentUser;
        // 头像
        String picUrl = StringUtils.appendPicPath(user.getUserPic());
        Picasso.with(this)
                .load(picUrl)
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(ivMePic);

        // 昵称
        etNickName.setText(user.getNickName());
        // 用户名
        tvUserName.setText(user.getUserName());
        // 名字
        etName.setText(user.getEmpName());
        if (user.getUserNote() != null && !user.getUserNote().equals(NO_NOTE)) {
            // 首次进来默认hint签名
            etNote.setText(user.getUserNote());
        }
    }

    /**
     * 初始化EMP基础信息
     * @param bean EMP
     */
    private void initEmpInfo(EmpNetBean bean) {
        // 联系电话
        tvTelephone.setText(bean.getTelphone());
        // 家庭住址
        etAddr.setText(bean.getAddr());
    }

    /**
     * 初始化事件
     */
    private void initEvent() {
        // 添加联系人
        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (NetConfig.currentUser == null) {
                    Toast.makeText(MeIndexActivity.this, getString(R.string.chat_lost_conn),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                update();
            }
        });

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        llPhoneContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MeIndexActivity.this, ChangePhoneCheckActivity.class);
                startActivity(intent);
            }
        });

        ivMePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetConfig.currentUser == null) {
                    Toast.makeText(MeIndexActivity.this,
                            getString(R.string.chat_lost_conn),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                addPhoto();
            }
        });

        tvEditIndex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean flag = RequestUtils.isNetworkConnected(MeIndexActivity.this);
                if (!flag) {
                    ToastUtils.toastContent(MeIndexActivity.this,
                            getString(R.string.tip_check_net));
                    return;
                }

                tvEditIndex.setVisibility(View.GONE);
                btnExit.setVisibility(View.GONE);
                tvSave.setVisibility(View.VISIBLE);
                setComponentEnable(true);
            }
        });

        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow = new ConfirmPopupWindow(MeIndexActivity.this,
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                popupWindow.dismiss();
                                logout();
                            }
                        },
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                popupWindow.dismiss();
                            }
                        });

                popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
            }
        });

        rlQrCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MeIndexActivity.this, QRCodeActivity.class);
                intent.putExtra("name", NetConfig.currentUser.getUserName());
                intent.putExtra("pic", NetConfig.currentUser.getUserPic());
                intent.putExtra("nick", NetConfig.currentUser.getNickName());
                startActivity(intent);
            }
        });
    }

    /**
     * 退出登录
     */
    private void logout() {
        // 取消自动登录，即标记自动登录为FALSE
        PreferenceUtils.putBoolean(this, Constants.AUTO_LOGIN, false);

        Intent intent1 = new Intent(this, MqttService.class);
        stopService(intent1);

        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

        startActivity(intent);
        finish();
    }

    /**
     * 点击添加图片，弹出popwindow。选择图库或拍照的图片。
     */
    private void addPhoto() {
        mPopWindom = new TakePicBottomPop(MeIndexActivity.this, itemsOnClick);
        mPopWindom.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
            }
        });
        mPopWindom.showAtLocation(MeIndexActivity.this.tvSave,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mPopWindom.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    // 照相
                    clickTakePhoto();
                    break;
                case R.id.btn_album:
                    // 相册
                    clickAlbum();
                    break;
                case R.id.btn_cancel:
                    mPopWindom.dismiss();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 点击相册（图库）
     */
    private void clickAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, SELECT_PIC);
    }

    /**
     * 点击拍照
     */
    private void clickTakePhoto() {
        File outputImage = new File(Environment
                .getExternalStorageDirectory(), "test" + System
                .currentTimeMillis() + ".jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        imageUri = Uri.fromFile(outputImage);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO); // 启动相机程序
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    sendPicture(imageUri.getEncodedPath());
                }
                break;

            case CROP_PHOTO:
                try {
                    if (resultCode == RESULT_OK) {
                        sendPicture(imageUri.getEncodedPath());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case SELECT_PIC:
                if (resultCode == RESULT_OK) {
                    sendPicture(PhotoUtils.getPath(this, data.getData()));
                }
                break;
            default:
                break;
        }
    }

    /**
     * 发送图片
     * @param path 图片路径
     */
    private void sendPicture(String path) {
        dialog = new WaitingDialog(this, "");
        dialog.setText(getString(R.string.uploading_head));
        dialog.show();
        ImageUtils imageUtils = new ImageUtils();
        Bitmap bitmap = imageUtils.ratio(path, (float) Constants.screenHeight / 2, (float) Constants
                .screenWidth / 2);
        byte[] bytes = null;
        try {
            bytes = imageUtils.getBitmapByte(bitmap);
        } catch (Exception e) {
            Toast.makeText(this, getString(R.string.chat_illegal_pic), Toast.LENGTH_SHORT).show();
            dialog.dismiss();
            return;
        }

        RequestUtils.updateUserHead(NetConfig.currentUser.getUserId(),
                Base64.encodeToString(bytes, Base64.DEFAULT),
                new RequestCallback() {

                    @Override
                    public void onError(Call call, Exception e) {
                        dialog.dismiss();
                        Toast.makeText(MyApplication.mCurrentActivity,
                                getString(R.string.chat_update_head_failed),
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        String result = responseBean.getEntity(String.class);
                        String resultCode = responseBean.getResultCode();
                        dialog.dismiss();
                        if (Constants.REQUEST_OK.equals(resultCode)) {
                            NetConfig.currentUser.setUserPic(result);
                            // 头像
                            String picUrl = StringUtils.appendPicPath(NetConfig.currentUser
                                    .getUserPic());
                            Picasso.with(MeIndexActivity.this)
                                    .load(picUrl)
                                    .placeholder(R.drawable.pic_talkbox_sel)
                                    .error(R.drawable.pic_talkbox_sel)
                                    .into(ivMePic);

                            Toast.makeText(MyApplication.mCurrentActivity,
                                    getString(R.string.chat_update_head_success),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MyApplication.mCurrentActivity,
                                    getString(R.string.chat_update_head_failed),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    /**
     * 添加
     */
    private void update() {
        final String nickName = etNickName.getText().toString();
        final String realName = etName.getText().toString();
        String addr = etAddr.getText().toString();
        final String note = etNote.getText().toString();
        if (StringUtils.isEmpty(nickName)) {
            Toast.makeText(this, getString(R.string.chat_pls_nick_name),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(realName)) {
            Toast.makeText(this, getString(R.string.chat_pls_real_name),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        RequestUtils.updateUserMsg(NetConfig.currentUser.getUserId(),
                nickName, realName, addr, note,
                new RequestCallback() {

                    @Override
                    public void onError(Call call, Exception e) {
                        e.printStackTrace();
                        Toast.makeText(MyApplication.mCurrentActivity,
                                getString(R.string.chat_update_failed), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        String result = responseBean.getEntity(String.class);
                        String resultCode = responseBean.getResultCode();
                        if (Constants.REQUEST_OK.equals(resultCode)) {
                            NetConfig.currentUser.setUserNote(note);
                            NetConfig.currentUser.setNickName(nickName);
                            NetConfig.currentUser.setEmpName(realName);
                            //重新保存用户数数据
                            String data = new Gson().toJson(NetConfig.currentUser);
                            PreferenceUtils.putString(MeIndexActivity.this, Constants.USER_DATA,
                                    data);
                            renderPanel();
                            Toast.makeText(MeIndexActivity.this, result,
                                    Toast.LENGTH_SHORT).show();
                            MeIndexActivity.this.setResult(RESULT_OK);
                            finish();
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
